namespace :language do
  desc "Initialize translation data"

  task (:init => :environment) do
    require "active_record"
    load_language_data
  end
end

def load_language_data
  table_name = 'globalize_translations'
  
  column_clause = nil
  is_header = false
  
  ActiveRecord::Base.establish_connection(
    YAML::load(File.open(RAILS_ROOT+'/config/database.yml'))[:environment]
  )
  
  cnx = ActiveRecord::Base.connection
  ActiveRecord::Base.silence do
    reader = CSV::Reader.create(File.open(RAILS_ROOT+'/config/init_translation.csv'))

    columns = reader.shift.map {|column_name| cnx.quote_column_name(column_name) }
    column_clause = columns.join(', ')

    reader.each do |row|
      next if row.first.nil? # skip blank lines
      raise "No table name defined" if !table_name
      raise "No header defined" if !column_clause
      values_clause = row.map {|v| cnx.quote(v).gsub('\\n', "\n").gsub('\\r', "\r") }.join(', ')
      sql = "INSERT INTO #{table_name} (#{column_clause}) VALUES (#{values_clause})"
      cnx.insert(sql)
    end
  end
end
